﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using QuanLyHopDong.Biz.Model;

namespace QuanLyHopDong.Biz
{
    public class HopDongBiz
    {
        #region Selection

        public List<HopDongView> GetHopDongViews(int startIndex, int pageSize, string sorting,
            string soHopDong, string tenHopDong, string tenDonVi,
            DateTime? ngayHoanThienFrom, DateTime? ngayHoanThienTo,
            DateTime? ngayQuyetToanFrom, DateTime? ngayQuyetToanTo,
            int trangThai, bool thiCongXong,
            Employee employee,
            int employeeId,
            out int totalRecords)
        {
            using (var db = new HopDongEntities())
            {
                var query = from item in db.HopDongViews select item;

                // filter
                if (employee != null)
                {
                    if (!employee.IsAdmin) // not admin
                    {
                        query = query.Where(x => x.EmployeeId == employee.Id);
                    }
                    else
                    {
                        if (employeeId > 0)
                        {
                            query = query.Where(x => x.EmployeeId == employeeId);
                        }
                    }
                }
                if (trangThai == 0)
                {
                    // list hop dong chua hoan thien
                    query = query.Where(x => x.TrangThai != 5);
                }
                else if (trangThai > 0)
                {
                    query = query.Where(x => x.TrangThai == trangThai);
                }
                if (thiCongXong)
                {
                    query = query.Where(x => x.ThiCongXong);
                }
                if (trangThai == 5)
                {
                    if (ngayHoanThienFrom.HasValue)
                    {
                        query = query.Where(x => x.NgayHoanThien >= ngayHoanThienFrom);
                    }
                    if (ngayHoanThienTo.HasValue)
                    {
                        query = query.Where(x => x.NgayHoanThien <= ngayHoanThienTo);
                    }
                }
                if (ngayQuyetToanFrom.HasValue)
                {
                    query = query.Where(x => x.NgayQuyetToan >= ngayQuyetToanFrom);
                }
                if (ngayQuyetToanTo.HasValue)
                {
                    query = query.Where(x => x.NgayQuyetToan <= ngayQuyetToanTo);
                }
                if (!string.IsNullOrWhiteSpace(soHopDong))
                {
                    query = query.Where(x => x.SoHopDong.Contains(soHopDong));
                }
                if (!string.IsNullOrWhiteSpace(tenHopDong))
                {
                    query = query.Where(x => x.TenHopDong.Contains(tenHopDong));
                }
                if (!string.IsNullOrWhiteSpace(tenDonVi))
                {
                    query = query.Where(x => x.TenDonVi.Contains(tenDonVi));
                }

                totalRecords = query.Count();

                return pageSize > 0
                           ? query.OrderBy(sorting).Skip(startIndex).Take(pageSize).ToList() //Paging
                           : query.ToList(); //No paging
            }
        }

        public HopDongView GetById(int id)
        {
            using (var db = new HopDongEntities())
            {
                return db.HopDongViews.FirstOrDefault(x => x.Id.Equals(id));
            }
        }

        public List<HopDongView> ExportHopDongs(string soHopDong, string tenHopDong, string tenDonVi,
            DateTime? ngayHoanThienFrom, DateTime? ngayHoanThienTo,
            DateTime? ngayQuyetToanFrom, DateTime? ngayQuyetToanTo,
            int trangThai, bool thiCongXong,
            Employee employee,
            int employeeId)
        {
            using (var db = new HopDongEntities())
            {
                var query = from item in db.HopDongViews select item;

                // filter
                if (employee != null)
                {
                    if (!employee.IsAdmin) // not admin
                    {
                        query = query.Where(x => x.EmployeeId == employee.Id);
                    }
                    else
                    {
                        if (employeeId > 0)
                        {
                            query = query.Where(x => x.EmployeeId == employeeId);
                        }
                    }
                }
                if (trangThai == 0)
                {
                    // list hop dong chua hoan thien
                    query = query.Where(x => x.TrangThai != 5);
                }
                else if (trangThai > 0)
                {
                    query = query.Where(x => x.TrangThai == trangThai);
                }
                if (thiCongXong)
                {
                    query = query.Where(x => x.ThiCongXong);
                }
                if (trangThai == 5)
                {
                    if (ngayHoanThienFrom.HasValue)
                    {
                        query = query.Where(x => x.NgayHoanThien >= ngayHoanThienFrom);
                    }
                    if (ngayHoanThienTo.HasValue)
                    {
                        query = query.Where(x => x.NgayHoanThien <= ngayHoanThienTo);
                    }
                }
                if (ngayQuyetToanFrom.HasValue)
                {
                    query = query.Where(x => x.NgayQuyetToan >= ngayQuyetToanFrom);
                }
                if (ngayQuyetToanTo.HasValue)
                {
                    query = query.Where(x => x.NgayQuyetToan <= ngayQuyetToanTo);
                }
                if (!string.IsNullOrWhiteSpace(soHopDong))
                {
                    query = query.Where(x => x.SoHopDong.Contains(soHopDong));
                }
                if (!string.IsNullOrWhiteSpace(tenHopDong))
                {
                    query = query.Where(x => x.TenHopDong.Contains(tenHopDong));
                }
                if (!string.IsNullOrWhiteSpace(tenDonVi))
                {
                    query = query.Where(x => x.TenDonVi.Contains(tenDonVi));
                }

                return query.ToList(); //No paging
            }
        }

        #endregion

        #region CRUD

        public void CreateHopDong(HopDong newHopDong)
        {
            //if(string.IsNullOrWhiteSpace(newHopDong.SoHopDong))
            //    throw new ApplicationException("SoHopDongKhongHopLe");

            using (var db = new HopDongEntities())
            {
                // check so hop dong da ton tai
                if (!string.IsNullOrEmpty(newHopDong.SoHopDong))
                {
                    var count = db.HopDongs.Count(x => x.SoHopDong == newHopDong.SoHopDong);
                    if (count > 0)
                    {
                        throw new ApplicationException("SoHopDongDaTonTai");
                    }
                }

                // check don vi
                var donvi = db.DonVis.FirstOrDefault(x => x.Ten.Equals(newHopDong.TenDonVi));

                if (donvi != null) // don vi da ton tai
                {
                    newHopDong.DonViId = donvi.Id;
                }
                else
                {
                    // add new don vi
                    var newDonvi = new DonVi
                    {
                        Ten = newHopDong.TenDonVi
                    };

                    db.DonVis.Add(newDonvi);
                    db.SaveChanges();

                    newHopDong.DonViId = newDonvi.Id;
                }

                db.HopDongs.Add(newHopDong);
                db.SaveChanges();

                // hopdong files
                if (newHopDong.HopDongDocs != null)
                {
                    foreach (var hopDongDoc in newHopDong.HopDongDocs)
                    {
                        if (!string.IsNullOrWhiteSpace(hopDongDoc.FileHopDong))
                        {
                            hopDongDoc.HopDongId = newHopDong.Id;
                            db.HopDongDocs.Add(hopDongDoc);
                        }
                    }
                    db.SaveChanges();
                }
            }
        }

        public void UpdateHopDong(HopDong hopDong)
        {
            using (var db = new HopDongEntities())
            {
                // check so hop dong da ton tai
                if (!string.IsNullOrEmpty(hopDong.SoHopDong))
                {
                    var count = db.HopDongs.Count(x => x.SoHopDong.Equals(hopDong.SoHopDong) && !x.Id.Equals(hopDong.Id));
                    if (count > 0)
                    {
                        throw new ApplicationException("SoHopDongDaTonTai");
                    }
                }

                // check don vi
                var donvi = db.DonVis.FirstOrDefault(x => x.Ten.Equals(hopDong.TenDonVi));

                if (donvi != null) // don vi da ton tai
                {
                    hopDong.DonViId = donvi.Id;
                }
                else
                {
                    // add new don vi
                    var newDonvi = new DonVi
                    {
                        Ten = hopDong.TenDonVi
                    };

                    db.DonVis.Add(newDonvi);
                    db.SaveChanges();

                    hopDong.DonViId = newDonvi.Id;
                }

                // update
                db.HopDongs.Attach(hopDong);
                db.Entry(hopDong).State = EntityState.Modified;
                db.SaveChanges();

                // hopdong files
                if (hopDong.HopDongDocs != null)
                {
                    foreach (var hopDongDoc in hopDong.HopDongDocs)
                    {
                        if (!string.IsNullOrWhiteSpace(hopDongDoc.FileHopDong))
                        {
                            hopDongDoc.HopDongId = hopDong.Id;
                            db.HopDongDocs.Add(hopDongDoc);
                        }
                    }
                    db.SaveChanges();
                }
            }
        }

        public void DeleteFileHopDong(string filePath, int hopDongId)
        {
            if (File.Exists(filePath))
                File.Delete(filePath);

            using (var db = new HopDongEntities())
            {
                db.DeleteFileHopDong(hopDongId);
            }
        }

        #endregion

        #region Quyet toan

        /*
        public void QuyetToan(QuyetToan quyetToan)
        {
            using (var db = new HopDongEntities())
            {
                // check exist
                var count = db.QuyetToans.Count(x => x.HopDongId.Equals(quyetToan.HopDongId));
                if (count > 0)
                {
                    // existing, update
                    db.QuyetToans.Attach(quyetToan);
                    db.Entry(quyetToan).State = EntityState.Modified;
                }
                else
                {
                    // create new
                    db.QuyetToans.Add(quyetToan);
                }

                db.SaveChanges();
            }
        }
        */
        #endregion

        public List<HopDongDoc> FileList(int hopDongId)
        {
            using (var db = new HopDongEntities())
            {
                return db.HopDongDocs.Where(x => x.HopDongId == hopDongId).ToList();
            }
        }

        public void FileDelete(int id)
        {
            using (var db = new HopDongEntities())
            {
                var hopDongDoc = new HopDongDoc { Id = id };
                db.HopDongDocs.Attach(hopDongDoc);
                db.Entry(hopDongDoc).State = EntityState.Deleted;

                db.SaveChanges();
            }
        }

        public void DeleteHopDong(int id, string folderPath)
        {
            // delete files
            if (Directory.Exists(folderPath))
                Directory.Delete(folderPath, true);

            // delete hopdong
            using (var db = new HopDongEntities())
            {
                db.DeleteHopDong(id);
            }
        }
    }
}
